using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AdminApi.Model;
using AdminApi.Options;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace AdminApi;

public class CustomJWTService
{
    private readonly JwtTokenOptions _jwtTokenOptions;

    public CustomJWTService(IOptionsMonitor<JwtTokenOptions> jwtTokenOptions)
    {
        _jwtTokenOptions = jwtTokenOptions.CurrentValue;
    }

    public string GetToken(UserRes user)
    {
        var claims = new List<Claim>()
        {
            new Claim("Name", user.Name),
            new Claim("Password", user.Password),
            new Claim("RoleName",user.RoleName.ToString()),
        };

        //需要加密：需要加密key:
        //Nuget引入：Microsoft.IdentityModel.Tokens
        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOptions.SecurityKey));

        SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        //token过期时间，10分钟有效期
        var expires = DateTime.Now.AddMinutes(10);

        //Nuget引入：System.IdentityModel.Tokens.Jwt
        JwtSecurityToken token = new JwtSecurityToken(
            issuer: _jwtTokenOptions.Issuer,
            audience: _jwtTokenOptions.Audience,
            claims: claims,
            expires: expires,
            signingCredentials: creds);

        string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
        return returnToken;
    }
}